package com.hershel.userservice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hershel.hershelcommonpackage.exception.DataBaseQueryNullException;
import com.hershel.userservice.entity.User;
import com.hershel.userservice.entity.UserDetails;
import com.hershel.userservice.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserService implements UserDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    public List<User> test() {
        List<User> user = userMapper.queryAll();
        return user;
    }

    @Override
    public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserDetails user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
//        return new UserDetailsImpl(username);
        return null;
    }

    /**
     * 注册用户
     *
     * @param user 用户
     * @return 数量
     */
    public int registerUser(UserDetails user) {
        String encryptPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encryptPassword);
        int insert = userMapper.insert(user);
        return insert;
    }

    /**
     * 登录
     *
     * @param username    用户名
     * @param rawPassword 密码
     * @return boolean
     */
    public boolean login(String username, String rawPassword) {
        LOGGER.info("username:{},rawPassword:{}", username, rawPassword);
        QueryWrapper<UserDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserDetails user = userMapper.selectOne(queryWrapper);
        LOGGER.info("user:{}", user);
        if (StringUtils.isEmpty(user)) {
            throw new DataBaseQueryNullException();
        }
        boolean result = rawPassword.equals(user.getPassword());
        LOGGER.info("密码比对结果为：{}", result);
        return result;
    }
}
